import * as Base64 from 'base64-arraybuffer-es6'

const coder = {}

coder.xorBytes = function (buffer, key) {
  var bufferLen = buffer.byteLength
  var keyLen = key.length
  var xors = new Uint8Array(bufferLen)

  var j=0
  for (var i=0; i<bufferLen; i++) {
    xors[i] = buffer[i] ^ key.charCodeAt(j++)
    if (j == keyLen) {
      j = 0
    }
  }

  return xors
}

coder.decode = function (base64String, key) {
  var decodeBuffer = Base64.decode(base64String)
  var uint8Buffer = new Uint8Array(decodeBuffer)

  var decodedBuffer = this.xorBytes(uint8Buffer, key)

  var decoded = new TextDecoder('ascii').decode(decodedBuffer);
  try {
    var json = JSON.parse(decoded)
    return json
  } catch (error) {
    console.log(error.message)
    return null
  }
}

export default coder
